/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LineChart.java
 *
 * Created on Sep 25, 2011, 8:07:33 PM
 */
package InterNalFrame;

import RunableClass.useClass.Addport;
import averages.EMA;
import averages.SMA;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.StringReader;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.labels.XYItemLabelGenerator;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.DateRange;
import org.jfree.data.time.Day;
import org.jfree.data.time.Month;
import org.jfree.data.time.MovingAverage;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;

/**
 *
 * @author Anatomy
 */
public class RSIChart extends javax.swing.JInternalFrame implements ChartMouseListener{
    private static int[] SMAP;
    private static int[] WMAP;
 JFreeChart     chart ;  
 ChartPanel     chartPanel;   
 XYPlot         plot,plot1 ;
 JLabel         LB,SymbolName;
 static JTextField     Symbol,Interval;
 CombinedDomainXYPlot Cplot ;
  public static ValueAxis domainAxis;
  public static int []EMAP;
 JComboBox JB;
static  TimeSeries series4[];
    private String Period="";
    private TimeSeries[] seriesSMA;
    private String SMASTRING="";
    private TimeSeries[] seriesWMA;
    private String WMASTRING="";
    /** Creates new form LineChart */
    public RSIChart() {
        initComponents();
        
    }
    String EMASTRING = "";
            
 public RSIChart(Dimension size,JTextField Symbol,JTextField Interval,JComboBox JB) throws SQLException {
     this.Symbol=Symbol;
     this.Interval=Interval;
      this.JB=JB;
      // t..hrow new UnsupportedOperationException("Not yet implemented");
          double height = size.getHeight()+10;
        double width = size.getWidth()+12;
            
          Dimension xy=new Dimension();
          xy.setSize(width, height);
           Dimension setroot=new Dimension();
          setroot.setSize(width, height);
       this.setSize(xy);
       this.setLocation(-5,-5);
//setRootPaneCheckingEnabled(false);
javax.swing.plaf.InternalFrameUI ifu= this.getUI();
((javax.swing.plaf.basic.BasicInternalFrameUI)ifu).setNorthPane(null);



     final XYDataset priceData = createRandomDataset();

        chart = ChartFactory.createTimeSeriesChart(
            null, 
            null, 
            null,
            priceData, 
            true,
            false,
            false
        );
      plot = chart.getXYPlot();
        final NumberAxis rangeAxis1 = (NumberAxis) plot.getRangeAxis();
        rangeAxis1.setLowerMargin(0.0); 
        ValueAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.0);
        domainAxis.setUpperMargin(0.0);
         plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT,false);

Calendar cal = Calendar.getInstance();
            int y = cal.get(Calendar.YEAR);
            int M = cal.get(Calendar.MONTH);
            int d = cal.get(Calendar.DAY_OF_MONTH);
            int h = cal.get(Calendar.HOUR_OF_DAY);
            int m = cal.get(Calendar.MINUTE);
            int s = cal.get(Calendar.SECOND);
            int i = cal.get(Calendar.MILLISECOND);
cal.clear();

if(STOCK.STOCK.cbAnalysis.getSelectedIndex()==0){
cal.set(y-Integer.parseInt(STOCK.STOCK.txtinterval.getText()), M, d);
 Date minDate = cal.getTime();
cal.clear();
//javax.swing.JOptionPane.showMessageDialog(null, y+"-"+M+"-"+d);
   cal.set(y, M, d);     

//cal.set(y , M, d);
Date maxDate = cal.getTime();
domainAxis.setRangeWithMargins( new DateRange(minDate.getTime() , maxDate.getTime() ) );
}
        // ValueAxis domainAxis1 = plot.getDomainAxis();   
        //domainAxis1.setVisible(true);//.setCategoryLabelPositions(CategoryLabelPositions.UP_45);   

        final XYItemRenderer renderer1 = plot.getRenderer();
        renderer1.setToolTipGenerator(
            new StandardXYToolTipGenerator(
                StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                new SimpleDateFormat("d-M-Y"), new DecimalFormat("0.00")
            )
        );
     
          //  renderer1.setSeriesPaint(1, Color.BLUE);
          //  renderer1.setSeriesPaint(2, Color.GREEN);
          //  renderer1.setSeriesPaint(3, Color.YELLOW);
        final XYItemRenderer renderer2 = plot.getRenderer();
        renderer2.setToolTipGenerator(
            new StandardXYToolTipGenerator(
                StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                new SimpleDateFormat("d-M-Y"), new DecimalFormat("0,000.00")
            )
        );
        // if(STOCK.STOCK.CbOpen.isSelected()){
        /// //    javax.swing.JOptionPane.showMessageDialog(null, dataset.getSeries(0));
         //  renderer1.setSeriesPaint(1, Color.BLUE); 
        ///}else
       /// if(STOCK.STOCK.CbHigh.isSelected()){
            //  javax.swing.JOptionPane.showMessageDialog(null, dataset.getSeries());
       //      renderer1.setSeriesPaint(2, Color.GREEN);
      //  }else
      ///  if(STOCK.STOCK.CbLow.isSelected()){
      //       renderer1.setSeriesPaint(3, Color.YELLOW);
      ///  }else
       // if(STOCK.STOCK.CbClose.isSelected()){
       ///     renderer1.setSeriesPaint(4, Color.RED);
       // }else{
            
//             renderer2.setSeriesPaint(4,randomColor());
     //   }
          

            
          




           
            
        chart.setPadding(RectangleInsets.ZERO_INSETS);
       //plot.setRenderer(1, renderer2);
       plot.setDomainCrosshairVisible(true);
        plot.setDomainCrosshairLockedOnData(true);
        plot.setDomainCrosshairPaint(Color.YELLOW);
          plot.setDomainCrosshairStroke(new BasicStroke(1.23f));
        plot.setRangeCrosshairVisible(true);
        plot.setRangeCrosshairPaint(Color.YELLOW);
        plot.setRangeCrosshairLockedOnData(true);
        plot.setRangeCrosshairStroke(new BasicStroke(1.23f));
        plot.setBackgroundPaint(Color.BLACK);
        
          chartPanel = new ChartPanel(chart);
          chartPanel= new ChartPanel(chart, true, true, true, false, true);
            chartPanel.addChartMouseListener(this);
            LB=new JLabel();
            LB.setText("");
            LB.setForeground(Color.yellow);
            JLabel LB1=new JLabel();
            LB1.setText("sddds");
       chartPanel.add(LB);  
         chartPanel.add(LB1);  
       setContentPane(chartPanel);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(224, Short.MAX_VALUE)
                .addComponent(LB)
                
                .addGap(136, 136, 136))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(LB)
                .addContainerGap(265, Short.MAX_VALUE))
        );
 }
   public XYDataset createDataset1() {

        final TimeSeries s1 = new TimeSeries("L&G European Index Trust", Month.class);
        s1.add(new Month(2, 2001), 181.8);
        s1.add(new Month(3, 2001), 167.3);
        s1.add(new Month(4, 2001), 153.8);
        s1.add(new Month(5, 2001), 167.6);
        s1.add(new Month(6, 2001), 158.8);
        s1.add(new Month(7, 2001), 148.3);
        s1.add(new Month(8, 2001), 153.9);
        s1.add(new Month(9, 2001), 142.7);
        s1.add(new Month(10, 2001), 123.2);
        s1.add(new Month(11, 2001), 131.8);
        s1.add(new Month(12, 2001), 139.6);
        s1.add(new Month(1, 2002), 142.9);
        s1.add(new Month(2, 2002), 138.7);
        s1.add(new Month(3, 2002), 137.3);
        s1.add(new Month(4, 2002), 143.9);
        s1.add(new Month(5, 2002), 139.8);
        s1.add(new Month(6, 2002), 137.0);
        s1.add(new Month(7, 2002), 132.8);


        
        final TimeSeries s2 = MovingAverage.createMovingAverage(
            s1, "Six Month Moving Average", 6, 0
        );

        final TimeSeriesCollection dataset = new TimeSeriesCollection();
        dataset.addSeries(s1);
        dataset.addSeries(s2);
        
        return dataset;

    }  public XYDataset createDataset2() throws SQLException {

        //  final TimeSeries series = new TimeSeries(name);
   /////////////////////////////////////////////////////
      //  final TimePeriodValues s1 = new TimePeriodValues(name);

          //  List<Double> data=new LinkedList();
          //   List<Integer> date2=new LinkedList();
           //   List<Integer> date1=new LinkedList();
           ///    List<Integer> date0=new LinkedList();
   
      
    
     
     ///////////////////////////////////////////////////////////
     
         TimeSeries series = new TimeSeries("Open_Base");
        TimeSeries series1 = new TimeSeries("High_Base");
      TimeSeries series2 = new TimeSeries("Low_Base");
       Connection connection = null;
        try {
        // Load the JDBC driver
        String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
        Class.forName(driverName);

        String serverName = "localhost";
        String mydatabase = "stock_data_base";
        String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
        // System.out.println("DataBase Connected");
        String username = "root";
        String password = "root";
        connection = (Connection) DriverManager.getConnection(url, username, password);
        System.out.println("DataBase Connected");

        Statement select = (Statement) connection.createStatement();
        ResultSet result = null;
       // javax.swing.JOptionPane.showMessageDialog(null, STOCK.txtSymbol.getText());
/* if(JB.getSelectedIndex()==0){
      result = select.executeQuery("SELECT * from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' AND DATE_SUB(CURDATE(),INTERVAL '"+Interval.getText()+"' YEAR) <= Date_Base");
 }else if(JB.getSelectedIndex()==1){
      result = select.executeQuery("SELECT * from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' AND DATE_SUB(CURDATE(),INTERVAL '"+Interval.getText()+"' MONTH) <= Date_Base");
 }else if(JB.getSelectedIndex()==2){
      result = select.executeQuery("SELECT * from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' AND DATE_SUB(CURDATE(),INTERVAL '"+Interval.getText()+"' DAY) <= Date_Base");   
 }
       */
              result = select.executeQuery("SELECT * from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"'");   

//ResultSet result = select.executeQuery("SELECT * from stock_base_banpu  where Ticker_Base='BANPU' AND Date_Base'2010-01-01'");

        //   result = select.executeQuery("SELECT * from stock_base_banpu  where Ticker_Base='BANPU' AND Date_Base=''");

        System.out.println("Got results:");
       // String str = "IBM";
   
        while (result.next()) {
                Date datadate = result.getDate(3);
                int price = result.getInt(5);
                int ma = result.getInt(6);
                 int ma1= result.getInt(7);
                    double ma2= result.getDouble(9);
               // System.out.println(datadate);
               // System.out.println(price);
               // System.out.println(ma);
                series.add(new Day(datadate),ma2);
               // series1.add(new Day(datadate),ma);
                //  series2.add(new Day(datadate),ma1);
                  
        }

	

      //   dataset.addSeries(series);
      //   dataset.addSeries(series1);
       //  dataset.addSeries(series2);
         
    //     dataset.addSeries(series1);

      
        }
        catch (ClassNotFoundException e) {
                System.out.println("DataBase Not Found");
        }
       

   

 
      // final TimePeriodValuesCollection dataset = new TimePeriodValuesCollection();
     //  dataset.addSeries(s1);
        //return dataset;
        
         TimeSeries s2 = MovingAverage.createMovingAverage(
            series,"MA", 6, 0
        );

         TimeSeriesCollection dataset1 = new TimeSeriesCollection();
        dataset1.addSeries(series);
        dataset1.addSeries(s2);
        
        return dataset1;

    }
    
  static   TimeSeriesCollection dataset;
    private XYDataset createRandomDataset() {
  //  final TimeSeries series = new TimeSeries(name);
   /////////////////////////////////////////////////////
      //  final TimePeriodValues s1 = new TimePeriodValues(name);

          //  List<Double> data=new LinkedList();
          //   List<Integer> date2=new LinkedList();
           //   List<Integer> date1=new LinkedList();
           ///    List<Integer> date0=new LinkedList();
   
     
    
     dataset=  new TimeSeriesCollection();
     ///////////////////////////////////////////////////////////
     
    
       Connection connection = null;
        try {
        // Load the JDBC driver
        String driverName = "com.mysql.jdbc.Driver"; // MySQL MM JDBC driver
        Class.forName(driverName);
        String serverName = "localhost";
        String mydatabase = "stock_data_base";
        String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
        String username = "root";
        String password = "root";
            try {
                connection = (Connection) DriverManager.getConnection(url, username, password);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        System.out.println("DataBase Connected");
        Statement select = null;
            try {
                select = (Statement) connection.createStatement();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
          ResultSet result1 = null;
            try {
                /// javax.swing.JOptionPane.showMessageDialog(null, STOCK.txtSymbol.getText());
         // if(JB.getSelectedIndex()==0){
               result1 = select.executeQuery("SELECT count(*) from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' ");
            } catch (SQLException ex) {
              javax.swing.JOptionPane.showMessageDialog(null, "Data not founded!","DATAERROR",JOptionPane.ERROR_MESSAGE);
            }
            try {
                /* }else if(JB.getSelectedIndex()==1){
                      result1 = select.executeQuery("SELECT count(*) from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' AND DATE_SUB(CURDATE(),INTERVAL '"+Interval.getText()+"' MONTH) <= Date_Base");
                 }else if(JB.getSelectedIndex()==2){
                      result1 = select.executeQuery("SELECT count(*) from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' AND DATE_SUB(CURDATE(),INTERVAL '"+(Integer.parseInt(Interval.getText())+20)+"' DAY) <= Date_Base");   
                 System.out.println("SELECT count(*) from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' AND DATE_SUB(CURDATE(),INTERVAL '"+(Integer.parseInt(Interval.getText())+20)+"' DAY) <= Date_Base");
                 } */
                 result1.next();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
         int row = 0;
            try {
                row = result1.getInt(1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            
        double vMA[]=new double[row];
        Date  VDate[]=new Date[row];
        
         ResultSet result2 = null;
            try {
                  result2 = select.executeQuery("SELECT * from stock_base_"+Symbol.getText().toLowerCase()+"  where Ticker_Base='"+Symbol.getText().toUpperCase()+"' ");   
         
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
 
    int count1=0;
            try {
                while (result2.next()) {
                      
                        int Open = result2.getInt(5);
                      
                            int Close= result2.getInt(8);
                       
                           vMA[count1]=(Open+Close)/2;
                           VDate[count1]=result2.getDate(3);
                          ++ count1;
                        // series4.add(new Day(datadate),(Open+Close)/2);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
  
    
         
          
                int[] Period1 = Period(STOCK.STOCK.WMAPeriod);
             RSIChart.WMAP=Period1; 
          seriesWMA = new TimeSeries[RSIChart.WMAP.length];
              WMASTRING="";
            for(int m=0;m<RSIChart.WMAP.length;m++){   
            System.out.println(RSIChart.WMAP[m]);
            seriesWMA[m]=new TimeSeries("WMA"+RSIChart.WMAP[m]);
            double[] wMA = new SMA(vMA,RSIChart.WMAP[m]).calc();
            WMASTRING+=("  SMA"+RSIChart.WMAP[m]+":"+roundTwoDecimals(wMA[wMA.length-1]));
            for(int i=0;i<wMA.length;i++){
                seriesWMA[m].add(new Day(VDate[i]),wMA[i]);
            }
                dataset.addSeries(seriesWMA[m]);
            }
              //   STOCK.STOCK.EMALB.setText(SMASTRING);
      
      
       //  dataset.addSeries(series2);
        }
        catch (ClassNotFoundException e) {
                System.out.println("DataBase Not Found");
        }
        return dataset;
    }
       private Random rand;


        public  Color randomColor()
    {
        return(new Color(rand.nextInt(256), 
                         rand.nextInt(256),
                         rand.nextInt(256)));
    }
 

          int CbHigh=0;
         // 
   int CbOpen=0,countCbEMA=0;
     int CbLow=0;      int CbClose=0;
     static TimeSeries  seriesEMA[];


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("jLabel1");

        jLabel2.setText("jLabel2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(224, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(96, 96, 96))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addContainerGap(293, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration//GEN-END:variables

    @Override
    public void chartMouseClicked(ChartMouseEvent cme) {
     //   throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void chartMouseMoved(ChartMouseEvent event) {
       
         int mouseX = event.getTrigger().getX(); 
        int mouseY = event.getTrigger().getY(); 
          Point2D p = chartPanel.translateScreenToJava2D( new Point(mouseX, mouseY)); 
        Rectangle2D plotArea = chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
        ValueAxis rangeAxis = plot.getRangeAxis(); 
          RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge(); 
      double chartY = rangeAxis.java2DToValue(p.getY(), plotArea, rangeAxisEdge); 
     LB.setText("Symbol:"+Symbol.getText().toUpperCase()+"   Y="+String.valueOf(roundTwoDecimals(chartY))+EMASTRING+SMASTRING);
  
     final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
        Stroke seriesStroke = renderer.getSeriesStroke(1);
        System.out.println(seriesStroke);
    }
      double roundTwoDecimals(double d) {
        	DecimalFormat twoDForm = new DecimalFormat("#.##");
		return Double.valueOf(twoDForm.format(d));
}
      
      public int[] Period(String textEMA){
     Scanner src = new Scanner(new StringReader(textEMA)); 
 int count=0;
    src.useDelimiter(", *"); 
 while(src.hasNext()) { 
      if(src.hasNextInt()) { 
 src.nextInt(); 
          count++; 
      }else{
        
      } 


 }
 int EMA[]=new int[count]; 
 int count1=0;
Scanner src1 = new Scanner(new StringReader(textEMA)); 
  src1.useDelimiter(", *"); 
 while(src1.hasNext()) { 
      if(src1.hasNextInt()) { 

       EMA[count1]=src1.nextInt(); 
      }
count1++;

 }
 //for(int i=0;i<EMA.length;i++){
   //  System.out.println(EMA[i]);
 //}
 
 return EMA;
}
      
 

}
